package examples.complex.view.maincontainer

import de.saxsys.mvvmfx.*
import de.saxsys.mvvmfx.internal.viewloader.View
import de.saxsys.mvvmfx.utils.notifications.NotificationCenter
import de.saxsys.mvvmfx.utils.viewlist.ViewListCellFactory
import examples.complex.view.personlogin.PersonLoginView
import examples.complex.view.personwelcome.PersonWelcomeView
import examples.complex.viewmodel.maincontainer.MainContainerViewModel
import examples.complex.viewmodel.personwelcome.PersonWelcomeViewModel
import javafx.beans.value.ChangeListener
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.scene.control.ListView
import javafx.scene.layout.StackPane

import javax.inject.Inject

/**
 * Created by Misty on 2015/6/6.
 */
class MainContainerView implements FxmlView<MainContainerViewModel>, Initializable {
    @FXML
    private StackPane loginView

    @FXML
    private PersonLoginView loginViewController

    @FXML
    private ListView<Integer> personWelcomeListView

    @Inject
    private NotificationCenter notificationCenter

    @InjectViewModel
    private MainContainerViewModel viewModel

    private Map<Integer, ViewTuple<PersonWelcomeView, PersonWelcomeViewModel>> viewMap = new HashMap<>()

    @Override
    void initialize(URL location, ResourceBundle resources) {
        notificationCenter.subscribe("hidePersonWelcome", { key, payload ->
            def personIdToHide = payload[0]
            viewModel.displayedPersons.remove(personIdToHide as Object)
        })
        loginViewController.viewModel.loggedInPersonIdProperty().addListener({ obs, oval, nval ->
            if (nval) {
                def id = nval.intValue()
                if (!viewModel.displayedPersons.contains(id)) {
                    println "ADD $id"
                    viewModel.displayedPersons.add(id)
                }
            }
        } as ChangeListener)

        final def cellFactory = new ViewListCellFactory<Integer>() {
            @Override
            ViewTuple<? extends View, ? extends ViewModel> map(Integer element) {
                if (!viewMap.containsKey(element)) {
                    def tuple = FluentViewLoader.fxmlView(PersonWelcomeView).load()
                    def codeBehind = tuple.codeBehind
                    codeBehind.viewModel.setPersonId(element)
                    viewMap.put(element, tuple)
                }
                return viewMap.get(element)
            }
        }
        personWelcomeListView.cellFactory = cellFactory
        personWelcomeListView.itemsProperty().bind(viewModel.displayedPersons)
    }
}
